package cn.openea.perpartner.crm.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.openea.perpartner.common.auth.entity.LoginBody;
import cn.openea.perpartner.common.auth.login.LoginService;
import cn.openea.perpartner.crm.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-12-01 19:06
 */
@Slf4j
@Component
public class CrmPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        LoginBody loginUser = loginService.loginCheck (request);
        if (BeanUtil.isEmpty(loginUser)) {
            UserContext.clear();
        }else {
            UserContext.setLoginUser(loginUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        UserContext.clear();
    }
}
